<template>
    <div class="mains">
        <div class="login-contain">

          <div class="panel">
            <span>{{player}}, {{cur_player}}, {{game_status}}</span>
<!--            <button @click="load_chess_game()">加载棋局</button>-->
            <button @click="exit_game()">退出比赛</button>
            <button @click="reset_chess_game()">复位棋局</button>
            <button @click="rewind_chess_game()">后退一步</button>
            <button @click="api_test()">测试</button>
          </div>

          <div class="chess-board">

            <div v-for="(row_status, row) in board_status" >

              <div v-for="(piece, col) in row_status" >
                <div class="piece" :class="get_piece_cls(piece, row, col)" @click="click_piece(piece, row, col)"></div>
              </div>

              <div style="clear: both"></div>
            </div>

          </div>


          <div>{{msg}}</div>
        </div>

    </div>
</template>

<script setup>
import { reactive, getCurrentInstance, onMounted, watch, ref } from 'vue'
import { ElMessage } from 'element-plus'
import {useStore} from 'vuex'
import { useRouter } from 'vue-router'
import cookies from 'js-cookie'
const instance = getCurrentInstance()
let name=ref('')
let password=ref('')
let board_status_data = [
  ["RJ1", "RM1", "RX1", "RS1", "RW", "RS2", "RX2", "RM2", "RJ2"],
  ["", "",  "",    "",    "",   "",    "",    "",    ""],
  ["",    "RP1", "",    "",    "",   "",    "",    "RP2", ""],
  ["RB1", "",    "RB2", "",    "RB3", "",   "RB4", "",    "RB5"],
  ["", "", "", "", "", "", "", "", ""],
  ["", "", "", "", "", "", "", "", ""],
  ["BB5", "", "BB4", "", "BB3", "", "BB2", "", "BB1"],
  ["", "BP2", "", "", "", "", "", "BP1", ""],
  ["", "", "", "", "", "", "", "", ""],
  ["BJ2", "BM2", "BX2", "BS2", "BW", "BS1", "BX1", "BM1", "BJ1"],
];
let board_status=ref(board_status_data)
let sel_piece = null
let sel_row = null
let sel_col = null
let player = 'B'
let msg = ref(0)
let match_id=0
let seq=0
let cur_player='R'
let game_status = 'G'

let player_move=null;
let opponent_move=null;

const {commit} =useStore()
const router = useRouter()

onMounted(()=>{
  console.log("Home onMounted.");
  let player_val = sessionStorage.getItem('player')
  match_id = parseInt(sessionStorage.getItem('match_id'))
  if (0==player_val) {
    player = 'R'
  } else if (1 == player_val) {
    player_val = 'B'
  } else {
    ElMessage.error('数据错误！')
    return;
  }
  // 加载棋局数据
  load_chess_game(match_id);
  // instance.proxy.$http.post('/api/v2.0/load_chess_game ', {
  //   "match_id": match_id
  // }).then((res) => {
  //   let error = res.error
  //   if (error == 0) {
  //     console.log("load_chess_game:", res)
  //   }else{
  //
  //   }
  // })
})

function login() {
    if (!name.value || !password.value) {
        ElMessage.error('请填写相应的信息！')
        return
    }
    let val = {
        username:name.value,
        password:password.value,
    }
    instance.proxy.$http.post('/api/v2.0/login ', val).then((res) => {
        let error = res.error
        if (error == 0) {
            ElMessage.success('登录成功')
            cookies.set('userid', val.username)
            sessionStorage.setItem('tokenAddFun',res.token)
            sessionStorage.setItem('userAddId',val.username)
            commit('updateName',val.username)
            router.push({
                name: 'Home',
            })
        }else{
            let arr1 =[
                'NOT_LOGIN',
                'USER_TYPE_WRONG',
                'PROC_WRONG',
                'PARAM_WRONG',
                'USER_NOT_EXIST',
                'PASSWORD_WRONG',
                'LOGIN_LOCKED',
                'USER_EXIST',
                'ZIP_PATH_WRONG',
                'PATH_EXIST',
                'RECORD_NOT_EXIST',
                'NO_PERMISSION',
                'SECCODE_WRONG'
            ]
            let arr2 =[
                1001,1002,1003,1004,1005,
                1006,1007,1008,1009,1010,
                1011,1012,1013
            ]
            let key =arr2.indexOf(error)
            if(key!=-1){
                ElMessage.error(arr1[key])
            }
        }
    })
}

function check_active_piece (piece, row, col) {
  // return false;
  if (piece == "")
    return false;
  if (row == sel_row && col == sel_col) {
    return true;
  } else {
    return false;
  }
}

function change_bord_status (cur_piece, move_to) {
  let piece = cur_piece[0], cur_row = cur_piece[1], cur_col = cur_piece[2];
  let move_row = move_to[1], move_col = move_to[2];
  let cur_bord_status = board_status.value;

  cur_bord_status[cur_row][cur_col] = ''
  cur_bord_status[move_row][move_col] = piece;
  board_status.value = cur_bord_status;
  // console.log('change:', this.board_status[cur_row][cur_col], cur_row, cur_col)
}

function chess_game_process(move) {

}

function cal_move(piece, cur_row, cur_col, move_row, move_col) {
  let cur_player = piece[0];

  // 现在玩家始终是处于棋盘下方。 棋盘坐标的计算也是固定的了。
  if ('B' == cur_player || true) {
     return [
         piece,
         [
           9-cur_col,
           10-cur_row
         ],
         [
           9 - move_col,
           10 - move_row
         ],
     ]
  } else if ('R' == cur_player) {
    return [
      piece,
      [
        cur_col+1,
        cur_row+1
      ],
      [
        move_col+1,
        move_row+1
      ],
    ]
  }
}

function cal_move_index(move) {
  let from_pos = move[1];
  let to_pos = move[2];
  let from_row = from_pos[1]-1, from_col = from_pos[0]-1;
  let to_row = to_pos[1]-1, to_col = to_pos[0]-1;
  return [from_row, from_col, to_row, to_col];
}

function reverse_rb_piece(status) {
  let piece_pos = {}
  status.forEach((row, r)=>{
    for (let i=0; i<row.length; i++){
      // if (row[i][0] == 'B') {
      //   row[i] = row[i].replace("B", "R")
      // } else if (row[i][0] == 'R') {
      //   row[i] = row[i].replace("R", "B")
      // }
      if (row[i].length) {
        piece_pos[row[i]] = [r,i]    // 保存棋子的位置
      }
    }
  })
  let new_status = new Array(10).fill().map(() => new Array(9).fill(""));
  for (let p in piece_pos) {
    let r=piece_pos[p][0];   // 行
    let c=piece_pos[p][1];   // 列
    new_status[9-r][8-c] = p;
  }
  return new_status;
}

function load_chess_game(match_id) {
  console.log('load_chess_game')
  instance.proxy.$http.post('/api/v2.0/load_chess_game', {
    'match_id':match_id,
  }).then((res)=>{
    console.log('res:', res)
    let error = res.error
    if (error == 0) {
      board_status.value = res.data.status;
      // player = res.data.player;
      // 如果是红色玩家， 红黑棋子要对调， 服务器端的数据是下面的棋子是黑方。
      if ("R" == player) {
        board_status.value = reverse_rb_piece(res.data.status)
      }
      sel_piece = null;
      sel_row = null;
      sel_col = null;
      seq = res.data.count;
      cur_player = res.data.player
      //
      let attack_w = res.data.attack_w;
      let kill_game = res.data.kill_game;
      if (kill_game) {
        game_status = 'K'
        ElMessage.warning('绝杀')
        return;
      } else if (attack_w) {
        ElMessage.warning('将军')
      }

      // 如果时对方走棋， 等待对方走棋。
      if (cur_player != player) {
        wait_opponent_move()
      }
    } else {
      ElMessage.error(res.err_msg)
    }
  })
}


function exit_game() {
  console.log('exit_game')
  instance.proxy.$http.post('/api/v2.0/game/exit', {
    'match_id':match_id,
    'player':player,
  }).then((res)=>{
    console.log('res:', res)
    let error = res.error
    if (error == 0) {
      sessionStorage.removeItem("match_id")
      sessionStorage.removeItem("player")
      router.push({
        name: 'Home',
      })
    } else {
      ElMessage.error(res.err_msg)
    }
  })
}


function reset_chess_game() {
  // 这里有一个经验， 调试用的固定参数用一个变量来表示， 修改的时候只用修改变量即可。
  return
  console.log('reset_chess_game')
  instance.proxy.$http.post('/api/v2.0/reset_chess_game', {
    'match_id':match_id,
  }).then((res)=>{
    console.log('res:', res)
    let error = res.error
    if (error == 0) {
      board_status.value = res.data.status;
      player = res.data.player;
      sel_piece = null;
      sel_row = null;
      sel_col = null;
    } else {
      ElMessage.error(res.err_msg)
    }
  })
}

function api_test() {
  instance.proxy.$http.post('/api/v2.0/test', {
    'match_id':24,
    'seq': 0
  }).then((res)=>{
    console.log('res:', res)

  })
}

function rewind_chess_game() {
  //
  return
  console.log('rewind_chess_game')
  instance.proxy.$http.post('/api/v2.0/rewind_chess_game', {
    'match_id':match_id,
  }).then((res)=>{
    console.log('res:', res)
    let error = res.error
    if (error == 0) {
      board_status.value = res.data.status;
      player = res.data.player;
      sel_piece = null;
      sel_row = null;
      sel_col = null;
    } else {
      ElMessage.error(res.err_msg)
    }
  })
}

function get_piece_cls(piece, row, col) {
  let res = {}
  let piece_cls = {
    'RW': 'red-w',
    'RS1': 'red-s',
    'RS2': 'red-s',
    'RX1': 'red-x',
    'RX2': 'red-x',
    'RM1': 'red-m',
    'RM2': 'red-m',
    'RJ1': 'red-j',
    'RJ2': 'red-j',
    'RP1': 'red-p',
    'RP2': 'red-p',
    'RB1': 'red-b',
    'RB2': 'red-b',
    'RB3': 'red-b',
    'RB4': 'red-b',
    'RB5': 'red-b',

    'BW': 'black-w',
    'BS1': 'black-s',
    'BS2': 'black-s',
    'BX1': 'black-x',
    'BX2': 'black-x',
    'BM1': 'black-m',
    'BM2': 'black-m',
    'BJ1': 'black-j',
    'BJ2': 'black-j',
    'BP1': 'black-p',
    'BP2': 'black-p',
    'BB1': 'black-b',
    'BB2': 'black-b',
    'BB3': 'black-b',
    'BB4': 'black-b',
    'BB5': 'black-b',

  }

  if (piece_cls[piece]) {
    res[piece_cls[piece]] = true
  }

  if (row == sel_row && col == sel_col) {
    res['active-piece'] = true;
  }

  let move_list = [player_move, opponent_move];
  let css_name = [['move-piece-from', 'move-piece-to'], ['move-piece-from-2', 'move-piece-to-2']]
  for (let i in move_list) {
    let move_info = move_list[i];
    if (move_info) {
      if(row == move_info[0] && col == move_info[1]) {
        res[css_name[i][0]] = true;
      }
      if(row == move_info[2] && col == move_info[3]) {
        res[css_name[i][1]] = true;
      }
    }
  }


  return res;
}

function update_opponent_status(move) {
  let piece = move[0];
  let from_pos = move[1];
  let to_pos = move[2];
  let from_row = from_pos[1]-1, from_col = from_pos[0]-1;
  let to_row = to_pos[1]-1, to_col = to_pos[0]-1;
  let status = board_status.value;
  if ('B' == piece[0]) {
    cur_player = 'R'
  } else if ('R' == piece[0]) {
    cur_player = 'B'
  } else {
    ElMessage.error("数据错误")
  }


  status[from_row][from_col] = ""
  status[to_row][to_col] = piece
}

function wait_opponent_move() {
  // console.log('move:', move)
  instance.proxy.$http.post('/api/v2.0/wait_opponent_move ', {
    'match_id':match_id,
    'player':player,
    'seq':seq
  }).then((res)=>{
    let error = res.error
    if (0 == error) {
      let move = res.move;

      update_opponent_status(move);

      opponent_move = cal_move_index(move);

      // 检查自己是否被将军。
      let check_player = player;

      // let attack_reverse = res.data.player_attack_reverse[check_player];
      // console.log('attack_reverse:', attack_reverse, check_player+'W')
      // if (attack_reverse[check_player+'W']) {
      //   ElMessage.warning('将军')
      // }
      let attack_w = res.data.attack_w;
      let kill_game = res.data.kill_game;
      if (kill_game) {
        game_status = 'K'
        ElMessage.warning('绝杀')
      } else if (attack_w) {
        ElMessage.warning('将军')
      }

    }
  })
}

function click_piece(piece, row, col) {
// if (piece == '' && this.sel_piece[0]=='')
  //   return;
  console.log("road:", piece, row, col, player.value);
  // 当前没有选中棋子
  if (!sel_piece) {
    // 没有点击到棋子
    if (!piece) {
      return;
    }
    // 选中的不是当前玩家的棋子
    if (piece[0] != player) {
      return;
    }
    sel_piece = piece;
    sel_row = row;
    sel_col = col;
  } else {
    // 当前有选中的棋子, 移动的位置是空的或是对方的棋子， 可以移动
    if (!piece || piece[0] != sel_piece[0]) {
      console.log('change_bord_status:', [sel_piece, sel_row, sel_col], [piece, row, col] )
      let move = cal_move(sel_piece, sel_row, sel_col, row, col)
      let player_move_save = [sel_row, sel_col, row, col];
      console.log('move:', move)
      instance.proxy.$http.post('/api/v2.0/chess_game_process ', {
        'match_id':match_id,
        'move':move
      }).then((res)=>{
        console.log('res 2:', res)
        let error = res.error
        if (error == 0) {
          change_bord_status([sel_piece, sel_row, sel_col], [piece, row, col]);

          sel_piece = null;
          sel_row = null;
          sel_row = null;

          // 实际对战是不切换的， 一个客户端固定为一方玩家。
          // if ('B' == player) {
          //   player = 'R';
          // } else if ('R' == player) {
          //   player = 'B';
          // }
          // 判断有没有将军
          cur_player = res.data.player

          let attack_w = res.data.attack_w;
          let kill_game = res.data.kill_game;
          if (kill_game) {
            game_status = 'K'
            ElMessage.warning('绝杀')
          } else if (attack_w) {
            ElMessage.warning('将军')
          }

          // let attack_reverse = res.data.player_attack_reverse[cur_player];
          // console.log('attack_reverse:', attack_reverse, cur_player+'W')
          // if (attack_reverse[cur_player+'W']) {
          //   ElMessage.warning('将军')
          // }
          // 判断是否胜利
          // let last_dead_piece = res.data.last_dead_piece;
          // if (last_dead_piece && last_dead_piece.length && 'W' == last_dead_piece[0][1]) {
          //   ElMessage.warning('胜利')
          // }
          seq = res.data.count
          player_move = player_move_save;
          console.log("player_move:", player_move)

          // 没有绝杀时,等待对方走棋
          if (!kill_game) {
            wait_opponent_move()
          }
        } else {
          ElMessage.error(res.err_msg)
        }
      })
      // change_bord_status([sel_piece, sel_row, sel_col], [piece, row, col]);

      // sel_piece = null;
      // sel_row = null;
      // sel_row = null;
      //
      // if ('B' == player) {
      //   player = 'R';
      // } else if ('R' == player) {
      //   player = 'B';
      // }
    } else {
      sel_piece = piece;
      sel_row = row;
      sel_col = col;
    }
  }
  msg.value = new Date().getTime();
}

</script>

<style  scoped>
.mains {
    /*background-image: url('../assets/bac.jpg');*/
    /*background-repeat: no-repeat;*/
    /*background-size: cover;*/
    width: 100vw;
    height: 100vh;
    display: flex;
    align-items: center;
}
.login-contain{
      width: 600px;
      height: 700px;
      padding: 0px;
      margin: 0 auto;
      display: flex;
      flex-flow: column;
      justify-content: center;
      align-items: center;
      align-self: center;
      /* background: #FFFFFF; */
      border-radius: 8px;
  }

.bord-col {
  float:left;
  height:30px;
  width:40px;
  display: flex; /* 设置容器为flex布局 */
  align-items: center; /* 水平居中对齐项目 */
  justify-content: center; /* 垂直居中对齐项目 */
  cursor: default;
}

.move-piece-from {
  /*text-decoration-line: underline;*/
  outline: dotted 1px green;
}

.move-piece-to {
  /*text-decoration-line: underline;*/
  outline: solid 1px green;
}

.move-piece-from-2 {
  /*text-decoration-line: underline;*/
  outline: dotted 1px blueviolet;
}

.move-piece-to-2 {
  /*text-decoration-line: underline;*/
  outline: solid 1px blueviolet;
}

.active-piece {
  /*text-decoration-line: underline;*/
  outline: solid 1px red;
}



.red-piece {
  color: red;
}

  .input{
      width: 350px;
      height: 40px;
      text-align: left;
      margin-top:10px;
  }
  .btn{
      margin-top: 30px;
      width: 350px;
      height: 40px;
      background-color: rgb(0, 150, 230);
      color: #fff;
      font-size: 20px;
  }
  .panel button {
    margin-left: 20px;
  }

  .chess-board {
    height:400px;
    width: 300px;
    background-image: url('../assets/img/象棋棋盘3.png');
    background-size: 269px 302px;
    background-position: 10px 11px;
    background-repeat: no-repeat;
  }

  .chess-board .piece {
    height:32px;
    width: 32px;
    /*border: solid 1px;*/
    float: left;
  }

  .red-w {
    background-image: url('../assets/img/棋子-红帅.png');
    background-size: 30px 30px;
    background-position: 0px 0px;
    background-repeat: no-repeat;
  }
  .red-s {
    background-image: url('../assets/img/棋子-红士.png');
    background-size: 30px 30px;
    background-position: 0px 0px;
    background-repeat: no-repeat;
  }
  .red-x {
    background-image: url('../assets/img/棋子-红相.png');
    background-size: 30px 30px;
    background-position: 0px 0px;
    background-repeat: no-repeat;
  }
.red-m {
  background-image: url('../assets/img/棋子-红马.png');
  background-size: 30px 30px;
  background-position: 0px 0px;
  background-repeat: no-repeat;
}
.red-j {
  background-image: url('../assets/img/棋子-红车.png');
  background-size: 30px 30px;
  background-position: 0px 0px;
  background-repeat: no-repeat;
}
.red-p {
  background-image: url('../assets/img/棋子-红炮.png');
  background-size: 30px 30px;
  background-position: 0px 0px;
  background-repeat: no-repeat;
}
.red-b {
  background-image: url('../assets/img/棋子-红兵.png');
  background-size: 30px 30px;
  background-position: 0px 0px;
  background-repeat: no-repeat;
}


.black-w {
  background-image: url('../assets/img/棋子-将.png');
  background-size: 30px 30px;
  background-position: 0px 0px;
  background-repeat: no-repeat;
}
.black-s {
  background-image: url('../assets/img/棋子-士.png');
  background-size: 30px 30px;
  background-position: 0px 0px;
  background-repeat: no-repeat;
}
.black-x {
  background-image: url('../assets/img/棋子-象.png');
  background-size: 30px 30px;
  background-position: 0px 0px;
  background-repeat: no-repeat;
}
.black-m {
  background-image: url('../assets/img/棋子-马.png');
  background-size: 30px 30px;
  background-position: 0px 0px;
  background-repeat: no-repeat;
}
.black-j {
  background-image: url('../assets/img/棋子-车.png');
  background-size: 30px 30px;
  background-position: 0px 0px;
  background-repeat: no-repeat;
}
.black-p {
  background-image: url('../assets/img/棋子-炮.png');
  background-size: 30px 30px;
  background-position: 0px 0px;
  background-repeat: no-repeat;
}
.black-b {
  background-image: url('../assets/img/棋子-卒.png');
  background-size: 30px 30px;
  background-position: 0px 0px;
  background-repeat: no-repeat;
}


/deep/ .el-input__inner{
      background-color: rgba(255,255,255,0) !important;
  }
  /deep/ .el-input__inner:-webkit-autofill{
      transition: background-color 5000s ease-in-out 0s;
  }
  /deep/ .el-input__inner:-webkit-autofill:focus{
      -webkit-text-fill-color: #333 !important;
  }
</style>
